package org.chmodke.proxy.client.select;

import org.chmodke.proxy.client.ProxyCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kehao
 */
public class GlobalProxySelector extends ProxySelector {
    private static final Logger logger = LoggerFactory.getLogger(GlobalProxySelector.class);
    private ProxySelector parent = ProxySelector.getDefault();

    private GlobalProxySelector() {

    }

    public static GlobalProxySelector getInstance() {
        return INNER.instance;
    }

    @Override
    public List<Proxy> select(URI uri) {
        // java.net.ProxySelector.setDefault
        logger.debug("query proxy for {}.", uri);
        String host = uri.getHost();
        int port = uri.getPort();

        Proxy proxy = ProxyCenter.getInstance().getRule(host, port);
        if (null != proxy) {
            logger.debug("found proxy {} for {}.", proxy, uri);
            List<Proxy> proxies = new ArrayList<>();
            proxies.add(proxy);
            return proxies;
        }
        logger.debug("default proxy for {}.", uri);
        return parent.select(uri);
    }

    @Override
    public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        logger.error("failed connect to {}.", uri, ioe);
    }

    private static class INNER {
        private static GlobalProxySelector instance = new GlobalProxySelector();
    }
}
